// Interface that interacts with database
// returns what is needed for the function that called it to work

var mysql = require('./database.js');
var timestamp = require('./timestamp.js');

var errorHandler = function (err, req, res) {

    res.render(req.path == '/' ? "home" : req.path.substring(1), {message: "Error: Connection to database unsuccessful", colour: 'red'});
    console.log("[" + timestamp.timeStamp() + "] Error: " + err.stack);
};

function isMobile(req) {

    var ua = req.headers['user-agent'];

    return /mobile/i.test(ua);
}

exports.getGameReadyUsers = function (req, res) {

    var connection = mysql.connectToDatabase(errorHandler, req, res);
    //var query = "SELECT userName FROM users WHERE onlineState = '2'";
    var query = "SELECT userName FROM users";

    connection.query(query, function (err, rows) {
        if (err) {

            errorHandler(err, req, res);

        } else {

            if (rows.length > 0) {

                connection.end();
                return rows;
            }
            return {};

        }
    });
};

exports.checkDuplicateUser = function (req, res, username, responseHandler) {

    var connection = mysql.connectToDatabase(errorHandler, req, res);
    var duplicateName = "SELECT userName FROM users WHERE userName ='" + username + "'";

    connection.query(duplicateName, function (err, rows) {

        if (err) {

            errorHandler(err, req, res);

        } else {

            if (rows.length > 0) {

                connection.end();
                responseHandler(true);

            }

            else {

                responseHandler(false);

            }
        }
    });
};

exports.insertUser = function (req, res, username, password, email) {

    var connection = mysql.connectToDatabase(errorHandler, req, res);

    var newUser = "INSERT INTO users (userName, password,email, onlineState, isAdmin) " +
        "VALUES ('" + username + "','" + password + "','" + email + "', 0, 0)";

    connection.query(newUser, function (err, rows) {

        if (err) {

            errorHandler(err, req, res);

        }
        else {

            connection.end();

        }
    });
}

exports.login = function (req, res, username, password, responseHandler) {

    if (req.session.username != null) {

        res.render("home", {message: "You are already logged in as " + req.session.username
            + ", if you wish to log in to another account please logout first", colour: 'orange'});

    }
    else {

        var connection = mysql.connectToDatabase(errorHandler, req, res);
        var onlineState = 1;

        if (isMobile(req)) {

            onlineState = 2;

        }

        var setOnlineState = "UPDATE users SET onlineState = '" + onlineState + "' WHERE userName ='" + req.body.username + "'";
        var verifyCredentials = "SELECT userName, isAdmin, onlineState FROM users WHERE userName ='"
            + req.body.username + "' AND password = '" + req.body.password + "'";

        connection.query(verifyCredentials, function (err, rows) {

            if (err) {

                errorHandler(err, req, res);

            } else {

                if (rows.length > 0 /*&& rows[0].onlineState === 0*/) {

                    connection.query(setOnlineState, function (err, rows) {

                        if (err) {

                            errorHandler(err, req, res);

                        }
                    });

                    connection.end();

                    req.session.username = rows[0].userName;
                    req.session.admin = rows[0].isAdmin == 1; //for flexibility between db type and js type, strict comparison not used

                    if (req.session.admin) {

                        console.log("User(Admin): " + rows[0].userName + " has logged in at " + timestamp.timeStamp());
                        responseHandler("admin");

                    }
                    else {

                        console.log("User: " + rows[0].userName + " has logged in at " + timestamp.timeStamp());
                        responseHandler("user");
                    }
                }
                else {

                    try {
                        if (rows[0].onlineState !== 0) {
                            connection.end();
                            responseHandler("logged in");
                        }
                    }
                    catch (err) {
                        connection.end();
                        responseHandler("incorrect input");
                    }

                }
            }
        });
    }
};

exports.logout = function (req, res, responseHandler) {

    if (req.session.username != null) {

        var setIsOnline = "UPDATE users SET onlineState = '0' WHERE userName ='" + req.session.username + "'";

        var connection = mysql.connectToDatabase(errorHandler, req, res);

        connection.query(setIsOnline, function () {});

        if (req.session.admin) {

            console.log("User(Admin): " + req.session.username + " has logged out at " + timestamp.timeStamp());
            responseHandler("admin");

        } else {

            console.log("User: " + req.session.username + " has logged out at " + timestamp.timeStamp());
            responseHandler("user");

        }
    }
};

exports.showMyDetails = function (req, res, responseHandler) {

    var connection = mysql.connectToDatabase(errorHandler, req, res);

    var UserDetailsSQL = "SELECT * FROM users WHERE userName = '" + req.session.username + "'";

    connection.query(UserDetailsSQL, function (err, rows) {

        if (err) {

            errorHandler(err, req, res);

        } else {

            if (rows.length > 0) {

                connection.end();

                if (req.session.admin) {

                    responseHandler("admin", rows);

                }
                else {

                    responseHandler("user", rows);
                }

            }
            else {

                connection.end();
                responseHandler("home");
            }
        }
    });
};

exports.editMyDetails = function (req, res, responseHandler) {

    var connection = mysql.connectToDatabase(errorHandler, req, res);

    var duplicateName = "SELECT userName FROM users WHERE userName ='" + req.body.userName + "'";
    var editDetails = "UPDATE users SET userName='" + req.body.userName + "', password='" + req.body.password
        + "', email='" + req.body.email + "' WHERE userName='" + req.session.username + "'";

    connection.query(duplicateName, function (err, rows) {

        if (err) {

            errorHandler(err, req, res);

        } else {

            if (rows.length > 0 && req.session.username != req.body.userName) {

                connection.end();
                responseHandler("in use");

            } else {

                connection.query(editDetails, function () {

                    console.log("User details have been changed at " + timestamp.timeStamp() + " : " + req.session.username + " -> " + req.body.userName);

                    req.session.username = req.body.userName;
                    responseHandler("successful");

                    connection.end();
                });
            }
        }
    });
};

exports.showAllUserDetails = function (req, res, responseHandler) {

    var connection = mysql.connectToDatabase(errorHandler, req, res);

    var database = "SELECT * FROM users";

    connection.query(database, function (err, rows) {

        if (err) {

            errorHandler(err, req, res);

        }
        else {

            if (rows.length > 0) {

                connection.end();
                responseHandler("successful", rows);

            }
            else {

                connection.end();
                responseHandler("failure", rows);

            }
        }
    });
};

exports.adminEditUser = function (req, res, userName, password, editThis, email, onlineState, isAdmin, responseHandler) {

    var connection = mysql.connectToDatabase(errorHandler, req, res);

    var duplicateName = "SELECT userName FROM users WHERE userName ='" + userName + "'";
    var editDetails = "UPDATE users SET userName='" + req.body.editThis + "', password='" + password + "', email='" + email + "', onlineState='" + onlineState + "', isAdmin='" + isAdmin + "' WHERE userName='" + userName + "'";

    connection.query(duplicateName, function (err, rows) {

        if (err) {

            errorHandler(err, req, res);

        } else {

            if (rows.length > 0 && editThis != userName) {

                connection.end();
                responseHandler("in use")

            } else {

                connection.query(editDetails, function () {

                    console.log("User details have been changed at " + timestamp.timeStamp() + " : " + editThis + " -> " + userName);
                    responseHandler("successful");
                    connection.end();
                });
            }
        }
    });
};


exports.AddFbUser = function (req, res, username, email) {

    console.log("6");

    var connection = mysql.connectToDatabase(errorHandler, req, res);

    var newUser = "INSERT INTO users (userName, password,email, onlineState, isAdmin) " +
        "VALUES ('" + username + "','" + "" + "','" + email + "', 0, 0)";

    console.log(newUser);

    connection.query(newUser, function () {

        console.log("7");
        connection.end();

    });
};

exports.CheckFbUserAdded = function (req, res, email, responseHandler) {

    console.log("1");

    var connection = mysql.connectToDatabase(errorHandler, req, res);
    var duplicateName = "SELECT email FROM users WHERE email ='" + email + "'";

    console.log(duplicateName);

    connection.query(duplicateName, function (err, rows) {

        console.log("2");
        console.log(rows);

        if (err) {

            errorHandler(err, req, res);
            connection.end();

        } else {

            console.log("HERE2");

            if (rows.length > 0) {

                connection.end();
                console.log("HERE3");

                console.log("3");
                responseHandler("true");

            } else {

                connection.end();
                console.log("HERE4");

                console.log("4");
                responseHandler("false");
            }
        }
    });
};

exports.FbLogins = function (req, res, username, responseHandler) {

    if (req.session.username != null) {

        res.render("home", {message: "You are already logged in as " + req.session.username
            + ", if you wish to log in to another account please logout first", colour: 'orange'});

    }
    else {

        var connection = mysql.connectToDatabase(errorHandler, req, res);
        var onlineState = 1;

        if (isMobile(req)) {
            onlineState = 2;
        }

        var setOnlineState = "UPDATE users SET onlineState = '" + onlineState + "' WHERE userName ='" + req.user.displayName + "'";
        var verifyCredentials = "SELECT userName, isAdmin, onlineState FROM users WHERE userName ='"
            + req.user.displayName + "'";

        connection.query(verifyCredentials, function (err, rows) {

            if (err) {

                errorHandler(err, req, res);

            } else {

                if (rows.length > 0 /*&& rows[0].onlineState === 0*/) {

                    connection.query(setOnlineState, function (err, rows) {

                        if (err) {
                            errorHandler(err, req, res);
                        }
                    });

                    connection.end();
                    req.session.username = rows[0].userName;
                    req.session.admin = rows[0].isAdmin == 1; //for flexibility between db type and js type, strict comparison not used

                    if (req.session.admin) {

                        console.log("User(Admin): " + rows[0].userName + " has logged in at " + timestamp.timeStamp());
                        responseHandler("admin");

                    }
                    else {

                        console.log("User: " + rows[0].userName + " has logged in at " + timestamp.timeStamp());
                        responseHandler("user");

                    }
                }
                else {

                    console.log("17");

                    try {
                        if (rows[0].onlineState !== 0) {
                            connection.end();
                            responseHandler("logged in");
                        }
                    }

                    catch (err) {
                        connection.end();
                        responseHandler("incorrect input");
                    }
                }
            }
        });
    }
};

